<?php
namespace app\farm\model;

use app\admin\model\ShopOrderRefund;
use app\BaseModel;
use app\farm\model\BalanceWater;

use app\massage\model\CouponRecord;
use app\massage\model\User;
use longbingcore\wxcore\PayModel;
use longbingcore\wxcore\PushMsgModel;
use think\facade\Db;

class ShopRefund extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_shop_refund_order';



     protected $append = [

         'order_goods',

         'address_info',

         'all_goods_num',

         'store_info',

         'refund_user_name'

     ];


    /**
     * @author chenniang
     * @DataTime: 2022-03-08 14:35
     * @功能说明:
     */
     public function getRefundUserNameAttr($value,$data){

         if(isset($data['refund_user'])&&isset($data['refund_user_admin'])){

             if($data['refund_user_admin']==1){

                 $model = new Admin();

                 $info = $model->where(['id'=>$data['refund_user']])->value('username');

             }else{

                 $model = new \app\farm\model\User();

                 $info = $model->where(['id'=>$data['refund_user']])->value('nickName');

             }

             return $info;

         }

     }


    /**
     * @author chenniang
     * @DataTime: 2022-03-07 17:38
     * @功能说明:
     */
    public function getStoreInfoAttr($value,$data){

        if(!empty($data['store_id'])){

            $farmer_model= new Farmer();

            $info = $farmer_model->dataInfo(['id'=>$data['store_id'],'type'=>2]);

            return $info;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 16:48
     * @功能说明:
     */
    public function getImgsAttr($value,$data){

        if(!empty($value)){

            return explode(',',$value);
        }

    }

    /**
     * @param $value
     * @param $data
     * @功能说明:总商品数量
     * @author chenniang
     * @DataTime: 2021-03-25 14:39
     */
    public function getAllGoodsNumAttr($value,$data){

        if(!empty($data['id'])){

            $order_goods_model = new ShopRefundGoods();

            $dis = [

                'refund_id' => $data['id']
            ];

            $num = $order_goods_model->where($dis)->sum('goods_num');

            return $num;
        }


    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-17 17:16
     * @功能说明:收货信息
     */
    public function getAddressInfoAttr($value,$data){

        if(!empty($data['order_id'])){

            $address_model = new OrderAddress();

            $info = $address_model->dataInfo(['order_id'=>$data['order_id']]);

            return $info;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-17 17:16
     * @功能说明:收货信息
     */
     public function getOrderGoodsAttr($value,$data){

         if(!empty($data['id'])){

             $goods_model = new ShopRefundGoods();

             $info = $goods_model->dataSelect(['refund_id'=>$data['id']]);

             return $info;

         }

     }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:37
     * @功能说明:后台列表
     */
    public function adminDataList($dis,$page=10,$mapor=[]){

        $data = $this->alias('a')

                ->join('lbfarm_shop_refund_order_goods c','a.id = c.refund_id')
                ->join('lbfarm_shop_order d','a.order_id = d.id')
                ->join('lbfarm_order_address e','a.order_id = e.order_id AND type = 5','left')
                ->where($dis)
                ->where(function ($query) use ($mapor){
                    $query->whereOr($mapor);
                })
                ->field('a.*,e.mobile,d.order_code as pay_order_code,e.user_name,d.pay_price')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();


        if(!empty($data['data'])){

            $user_model = new User();

            foreach ($data['data'] as &$v){

                $v['nickName'] = $user_model->where(['id'=>$v['user_id']])->value('nickName');

            }
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:46
     * @功能说明:小程序退款列表
     */
    public function indexDataList($dis,$where=[],$page=10){

        $data = $this->alias('a')
            ->join('lbfarm_shop_refund_order_goods c','a.id = c.refund_id')
            ->join('lbfarm_shop_order d','a.order_id = d.id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->field('a.*,d.order_code as pay_order_code')
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-08 17:08
     * @功能说明:退款中
     */
    public function refundIng($cap_id){

        $dis = [

            'cap_id' => $cap_id,

            'status' => 1
        ];

        $count = $this->where($dis)->count();

        return $count;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['status'] = 1;

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 09:37
     * @功能说明:通过退款
     */
    public function passOrder($id,$price,$payConfig,$refund_user=0,$text='',$id_admin=0){

        $refund_order= $this->dataInfo(['id'=>$id]);

        $order_model = new ShopOrder();

        $pay_order   = $order_model->dataInfo(['id'=>$refund_order['order_id']]);

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'订单状态错误'];
        }

        $update = [

            'refund_user' => $refund_user,

            'status'      => 2,

            'refund_time' => time(),

            'refund_price'=> $price,

            'pay_price'   => $price,

            'refund_text' => $text,

            'refund_user_admin' => $id_admin
        ];

        Db::startTrans();

        $res = $this->dataUpdate(['id'=>$refund_order['id']],$update);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试'];

        }
        //修改退款子订单的退款状态
        $order_refund_goods = new ShopRefundGoods();

        $res = $order_refund_goods->dataUpdate(['refund_id'=>$id],['status'=>2]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试1'.$res];

        }

        $goods_model = new ShopGoods();

        //退换库存
        foreach ($refund_order['order_goods'] as $v){

            $res = $goods_model->setOrDelStock($v['goods_id'],$v['spe_id'],$v['goods_num'],1,1,0,$v['kill_atv_id']);

            if(!empty($res['code'])){

                Db::rollback();

                return $res;

            }

        }

        $res = $order_model->dataUpdate(['id'=>$refund_order['order_id']],['true_price'=>$pay_order['true_price']-$price]);
        //查看货是否退完了
        $refund_success = $this->checkRefundNum($refund_order['order_id']);
        //退完了 就修改订单状态
        if($refund_success==1){

            $res = $order_model->dataUpdate(['id'=>$refund_order['order_id']],['pay_type'=>-1]);
            //退换优惠券
            $coupon_model = new CouponRecord();
//
//            $coupon_model->couponRefund($pay_order['id'],2);
//            if($res==0){
//
//                Db::rollback();
//
//                return ['code'=>500,'msg'=>'退款失败，请重试2'];
//
//            }

        }

        $pay_order   = $order_model->dataInfo(['id'=>$refund_order['order_id']]);

        $refund_order= $this->dataInfo(['id'=>$id]);


        $res = $this->refundCash($payConfig,$pay_order,$price,$refund_order);

        if(!empty($res['code'])){

            Db::rollback();

            return ['code'=>500,'msg'=>$res['msg']];
        }

        if($res!=true){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试3'];
        }

        Db::commit();

        $sys_model = new PushMsgModel($refund_order['uniacid']);

        $sys_model->sendMsg($refund_order,6);

        return true;

    }

    /**
     * @param $payConfig
     * @param $pay_order
     * @param $price
     * @param int $refund_id
     * @功能说明:退钱
     * @author chenniang
     * @DataTime: 2021-07-12 20:31
     */
    public function refundCash($payConfig,$pay_order,$price,$refund_order){

        if($price<=0){

            return true;
        }

        $water_model = new FinanceWater();
        //说明订单已经完成
        if($pay_order['type']=-1){
            //将流水状态修改为可入账
            $water_model->dataUpdate(['order_id'=>$pay_order['id'],'type'=>8],['cash_status'=>1]);
            //增加退款流水
            $water_model->addWater($refund_order['id'],9,2,1);
            //如果有运费将运费也改为可入账
            $water_model->dataUpdate(['order_id'=>$pay_order['id'],'type'=>16],['cash_status'=>1]);
            //增加运费退款流水
            $water_model->addWater($refund_order['id'],17,1,1);

        }else{

            $water_model->addWater($refund_order['id'],9,2,0);

            $water_model->addWater($refund_order['id'],17,1,0);

        }

        $water_model->cashArrival();

        if($pay_order['pay_model']==1){
            //微信退款
            $response = orderRefundApi($payConfig,$pay_order['pay_price'],$price,$pay_order['transaction_id']);
            //如果退款成功修改一下状态
            if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

                $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$pay_order['order_code'];

                $this->dataUpdate(['id'=>$refund_order['id']],['out_refund_no'=>$response['out_refund_no']]);

            }else {
                //失败就报错
                $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

                return ['code'=>500,'msg'=> $discption];

            }

        }elseif($pay_order['pay_model']==2){


            $data = [

                'user_id'  => $pay_order['user_id'],

                'pay_price'=> $price,

                'id'       => $refund_order['id'],

                'uniacid'  => $pay_order['uniacid']
            ];

            $water_model = new \app\farm\model\BalanceWater();

            $res = $water_model->addWater($data,10,1);

            if($res==0){

                return false;

            }



        }else{
            //支付宝
            $pay_model = new PayModel($payConfig);

            $res = $pay_model->aliRefund($pay_order['transaction_id'],$pay_order['pay_price']);

            if(isset($res['alipay_trade_refund_response']['code'])&&$res['alipay_trade_refund_response']['code']==10000){

                $this->dataUpdate(['id'=>$pay_order['id']],['out_refund_no'=>$res['alipay_trade_refund_response']['out_trade_no']]);

            }else{

                return ['code'=>500,'msg'=> $res['alipay_trade_refund_response']['sub_msg']];

            }
        }

        return true;

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-18 10:29
     * @功能说明:检查改订单款退完了没
     */
    public function checkRefundNum($order_id,$status=2){

        $order_goods_model = new ShopOrderGoods();

        $order_refund_goods_model = new ShopRefundGoods();

        $dis = [

            'order_id' => $order_id
        ];

        $goods_num = $order_goods_model->where($dis)->sum('goods_num');

        if($status==2){

            $dis['status'] = 2;

            $refund_num= $order_refund_goods_model->where($dis)->sum('goods_num');
        }else{

            $refund_num= $order_refund_goods_model->where($dis)->where('status','in',[1,2])->sum('goods_num');
        }

        return $refund_num>=$goods_num?1:0;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-18 15:38
     * @功能说明:该天的退款
     */
    public function datePrice($date,$uniacid,$cap_id=0,$end_time='',$type=1){

        $end_time = !empty($end_time)?$end_time:$date+86399;

        $dis = [];

        $dis[] = ['status','=',2];

        $dis[] = ['create_time','between',"$date,$end_time"];

        $dis[] = ['uniacid',"=",$uniacid];

        if(!empty($cap_id)){

            $dis[] = ['cap_id','=',$cap_id];
        }

        if($type==1){

            $price = $this->where($dis)->sum('refund_price');

            return round($price,2);

        }else{

            $count = $this->where($dis)->count();

            return $count;
        }


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 13:33
     * @功能说明:申请退款
     */
    public function applyRefund($order,$input){

        $order_goods_model = new ShopOrderGoods();

        $refund_price = 0;

        $integral = 0;

        Db::startTrans();

        $list = $input['list'];

        foreach ($list as $k=>$value){

            $order_goods = $order_goods_model->dataInfo(['id'=>$value['id']]);

            if(empty($order_goods)){

                return ['code'=>500,'msg'=>'商品未找到'];
            }

            if($value['num']>$order_goods['can_refund_num']||$value['num']==0){

                return ['code'=>500,'msg'=>'退款数量错误'];

            }
            //退款金额
            $refund_price += $order_goods['singe_pay_price']*$value['num'];


            $list[$k]['goods_id']    = $order_goods['goods_id'];

            $list[$k]['goods_name']  = $order_goods['goods_name'];

            $list[$k]['goods_cover'] = $order_goods['goods_cover'];

            $list[$k]['spe_name']    = $order_goods['spe_name'];

            $list[$k]['spe_id']      = $order_goods['spe_id'];

            $list[$k]['goods_price'] = $order_goods['goods_price'];

            $list[$k]['kill_atv_id'] = $order_goods['kill_atv_id'];

            $res = $order_goods_model->where(['id'=>$value['id']])->update(['can_refund_num'=>$order_goods['can_refund_num']-$value['num']]);

            if($res!=1){

                Db::rollback();

                return ['code'=>500,'msg'=>'申请失败'];

            }

        }

//        if($refund_price<=0){
//
//            Db::rollback();
//
//            return ['code'=>500,'msg'=>'退款金额至少为0.01元'];
//        }

        $refund_price = round($refund_price,2);

        $refund_price = $refund_price<=$order['pay_price']?$refund_price:$order['pay_price'];

        $insert = [

            'uniacid'    => $order['uniacid'],

            'store_id'   => $order['store_id'],

            'user_id'    => $order['user_id'],

            'farmer_id'  => $order['farmer_id'],

            'order_code' => orderCode(),

            'apply_price'=> $refund_price,

            'order_id'   => $order['id'],

            'text'       => $input['text'],

            'imgs'       => !empty($input['imgs'])?implode(',',$input['imgs']):''
        ];

        $res = $this->dataAdd($insert);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'申请失败'];

        }

        $refund_id = $this->getLastInsID();

        $refund_goods_model = new ShopRefundGoods();

        foreach ($list as $value){

            $insert = [

                'uniacid'        => $order['uniacid'],

                'order_id'       => $order['id'],

                'refund_id'      => $refund_id,

                'order_goods_id' => $value['id'],

                'goods_id'       => $value['goods_id'],

                'goods_name'     => $value['goods_name'],

                'goods_cover'    => $value['goods_cover'],

                'spe_name'       => $value['spe_name'],

                'spe_id'         => $value['spe_id'],

                'goods_num'      => $value['num'],

                'goods_price'    => $value['goods_price'],

                'kill_atv_id'    => $value['kill_atv_id'],

                'status'         => 1
            ];

            $res = $refund_goods_model->dataAdd($insert);

            if($res!=1){

                Db::rollback();

                return ['code'=>500,'msg'=>'申请失败'];

            }

        }
        //查看货是否退完了
        $refund_success = $this->checkRefundNum($order['id'],1);
        //退完并且未发货 就退运费
        if($refund_success==1&&$order['pay_type']<3){

            $refund_price += $order['freight'];

            $refund_price = $refund_price<=$order['pay_price']?$refund_price:$order['pay_price'];

            $this->dataUpdate(['id'=>$refund_id],['apply_price'=>$refund_price,'car_price'=>$order['freight']]);

        }

        Db::commit();

        return $refund_id;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-12 09:23
     * @功能说明:获取订单已经退款的数量
     */
    public function refundNum($order_goods_id){

        $dis = [

            'b.order_goods_id' => $order_goods_id,

            'a.status'   => 2
        ];

        $num = $this->alias('a')
                ->join('lbfarm_shop_refund_order_goods b','a.id = b.refund_id')
                ->where($dis)
                ->group('b.order_goods_id')
                ->sum('b.goods_num');

        return $num;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-12 09:23
     * @功能说明:获取订单已经退款的数量
     */
    public function orderRefundIng($order_goods_id){

        $dis = [

            'b.order_goods_id' => $order_goods_id,

            'a.status' => 1
        ];

        $num = $this->alias('a')
            ->join('lbfarm_shop_refund_order_goods b','a.id = b.refund_id')
            ->where($dis)
            ->group('b.order_goods_id')
            ->find();

        return !empty($num)?1:0;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-12 12:04
     * @功能说明:拒绝退款
     */
    public function noPassRefund($refund_id,$refund_user=0,$is_admin=0){

        $dis = [

            'id' => $refund_id
        ];

        $refund_order = $this->dataInfo($dis);

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'退款状态错误'];

        }

        $update = [

            'status'      => 3,

            'refund_time' => time(),

            'refund_user' => $refund_user,

            'refund_user_admin' => $is_admin

        ];

        Db::startTrans();

        $res = $this->dataUpdate($dis,$update);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试1'];

        }
        //修改退款子订单的退款状态
        $order_refund_goods = new ShopRefundGoods();

        $res = $order_refund_goods->dataUpdate(['refund_id'=>$refund_id],['status'=>3]);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试2'];

        }
        //查询通支付订单未退款对售后订单
        $where[] = ['order_id','=',$refund_order['order_id']];

        $where[] = ['status','=',1];

        $where[] = ['car_price','>',0];

        $find = $this->dataInfo($where);

        if(!empty($find)){

            $apply_price = $find['apply_price'] - $find['car_price'];

            $apply_price = $apply_price>0?$apply_price:0;

            $update = [

                'apply_price' => $apply_price,

                'car_price'   => 0
            ];

            $this->dataUpdate(['id'=>$find['id']],$update);
        }

        Db::commit();

        return true;

    }










}